package com.oktest.measure.ui.fragment.home

import android.os.Bundle
import com.cali.common.constant.EventSimple
import com.cali.common.kt.post
import com.cali.common.kt.value
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.http.RetrofitManagement
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.http.Api
import com.oktest.measure.kt.API_SUCCESS_CODE
import com.oktest.measure.kt.EVENT_HOME_TASK_REFRESH
import com.oktest.measure.kt.NOTICE_ID
import com.oktest.measure.kt.resultTryContext
import kotlinx.android.synthetic.main.fragment_notice_detail.*
import kotlinx.coroutines.launch

/**
 * @Author hhh
 * @Date 2020/9/19
 */
class HomeNoticeDetailFragment : BaseFragment() {
    override fun getLayoutId(): Int {
        return R.layout.fragment_notice_detail
    }

    override fun initData(savedInstanceState: Bundle?) {
        toolbarHelper?.setTitleText("公告")
        val noticeId = arguments.value(NOTICE_ID)
        getDetail(noticeId)
    }

    private fun getDetail(noticeId: String) = launch {
        val detailResult = resultTryContext {
            RetrofitManagement.instance.getService(Api::class.java)
                .noticeDetail(noticeId).execute().body()
        }
        detailResult.data?.apply {
            tvNoticeTitle.text = title
            tvNoticeContent.text = content
            tvNoticeTime.text = createTime
        }
        if (detailResult.code == API_SUCCESS_CODE) {
            MyApp.roomDatabase.homeNoticeDao().load(noticeId)?.apply {
                this.isNew = false
                MyApp.roomDatabase.homeNoticeDao().update(this)
            }
            EventSimple(EVENT_HOME_TASK_REFRESH).post()
        } else {
            error(detailResult)
        }
    }

    override fun hasToolbar(): Boolean {
        return true
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }
}